import logging, email, re, hashlib

from google.appengine.ext import webapp 
from google.appengine.ext.webapp.mail_handlers import InboundMailHandler 
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import namespace_manager

import parser, vdb
from vdb import Message

re_user = re.compile('^/_ah/mail/([0-9A-Za-z._-]{0,30})%40voismailer.appspotmail.com$')

class MailHandler(InboundMailHandler):
    def receive(self, msg):
        logging.info("Received a message from: " + self.request.path)
        m = re_user.match(self.request.path)
        if m is None:
            logging.error(self.request.path)
            logging.error(str(msg.original.items()))
        plaintext = msg.bodies(content_type='text/plain')
        logging.info('from: [' + m.group(1) + ']')
        namespace_manager.set_namespace(hashlib.md5(m.group(1)).hexdigest())
        item = Message(subject = msg.subject, date = parser.parse_date(msg.date),
                       sender = msg.sender, parsed = False)
        for text in plaintext:
            try:
                item.body = text[1].decode()
            except:
                item.body = text[1]

        item.put()
        records = parser.parse(item.body)
        if records[0][1] == 'common':
            records = parser.parse(item.subject)
        logging.info('parsed: ' + str(records[0]) + ', subj: ' + item.subject)
        vdb.msg_update_from(item, records[0])
        vdb.stat_update(item)
        if len(records) > 1:
            for record in records[1:]:
                logging.info('parsed: ' + str(record))
                rec = vdb.msg_clone(item)
                vdb.msg_update_from(rec, record)
                vdb.stat_update(rec)


application = webapp.WSGIApplication([MailHandler.mapping()], debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()

